﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using GT.Algorithms;
using GT.Ultilities;

namespace GT.App
{
    public partial class Documents : Form
    {
		private GST _gst;
		private static Documents _instance;
		public static Documents Instance
		{
			get
			{
				if (_instance == null) _instance = new Documents();
				return _instance;
			}
		}
		
        #region Constructors
        public Documents()
        {
            try
            {
                InitializeComponent();
//                 this._dgvDocument.AutoGenerateColumns = false;
//                 this._dgvDocument.DataSource = GT.DataAccess.GTDataContext.Context.Documents;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
        #endregion        
        #region Events
        private void _btnOpen_Click(object sender, EventArgs e)
        {
            try
            {
                Open();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

        }
        private void _btnPreprocess_Click(object sender, EventArgs e)
        {
            try
            {
                Preprocess();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
        private void _btnConstructGST_Click(object sender, EventArgs e)
        {
            GST.NewGST += new EventHandler<NewEventArgs>((s, a) =>
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        _gst = a.New;
                        this._trvGST.Nodes.Clear();
                        this._trvGST.Nodes.Add("/");
                        this._trvGST.Nodes[0].Tag = _gst.Root;
                        AddNodes(this._trvGST.Nodes[0]);
                    }));
                }
            });
			GST.Report += new EventHandler<ReportEventArgs>((s, a) =>
			{
				if (this.InvokeRequired)
				{
					this.Invoke(new MethodInvoker(() =>
					{
						this._pbrProcessing.Style = ProgressBarStyle.Blocks;
						this._lblMessage.Text = a.Action;
						this._pbrProcessing.Value = a.Percentage;
					}));
				}
			});
            GST.New(this._rbxPreprocessText.Text);
        }
		private void _trvGST_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			AddNodes(e.Node);
			foreach (TreeNode x in e.Node.Nodes)
			{
				AddNodes(x);
			}
		}
		private void _btnInsert_Click(object sender, EventArgs e)
		{
			try
			{
// 				Document doc = new Document(Guid.NewGuid(), Guid.NewGuid().ToString());
// 				doc.Insert();
// 				this._dgvDocument.DataSource = GT.DataAccess.GTDataContext.Context.Documents.GetNewBindingList();
			}
			catch (SqlException exc)
			{
				//MessageBox.Show("Tệp tin này đã tồn tại trong cơ sở dữ liệu!", "Thông báo lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				MessageBox.Show(exc.Message);
			}
		}
		private void _btnDelete_Click(object sender, EventArgs e)
		{
			try
			{
// 				foreach (DataGridViewRow dgvr in this._dgvDocument.SelectedRows)
// 				{
// 					(dgvr.DataBoundItem as GT.DataAccess.Document).Delete();
// 				}
// 				this._dgvDocument.DataSource = GT.DataAccess.GTDataContext.Context.Documents.GetNewBindingList();
			}
			catch (SqlException exc)
			{
				MessageBox.Show(exc.Message);
			}
		}
		#endregion
        #region Private Methods
        /// <summary>
        /// Chọn tệp tin.
        /// </summary>
        private void Open()
        {
            if (this._odgOpenDocument.ShowDialog() == DialogResult.OK)
            {
                this._rbxDocumentText.Text = ToText(this._odgOpenDocument.FileName);
            }
        }
        /// <summary>
        /// Tiền xử lý.
        /// </summary>
        private void Preprocess()
        {
            this._tpPreprocess.Select();
            this._rbxPreprocessText.Text = GST.Preprocess(this._rbxDocumentText.Text);
        }

		private void AddNodes(TreeNode x)
		{
			if (x.Nodes.Count > 0) return;
			Node n = x.Tag as Node;
			if (n.Node0 != null)
			{
				TreeNode x1 = new TreeNode(n.Node0.NodeText);
				x1.Tag = n.Node0;
				x.Nodes.Add(x1);
				Node next = n.Node0.Next;
				while (next != null)
				{
					TreeNode x2 = new TreeNode(next.NodeText);
					x2.Tag = next;
					x.Nodes.Add(x2);
					next = next.Next;
				}
			}
		}
        #endregion
		#region Static Methods
		/// <summary>
        /// Đọc văn bản
        /// </summary>
        /// <param name="path">Đường dẫn đến tệp tin.</param>
        /// <returns>Nội dung văn bản.</returns>        
        public static string ToText(string path)
        {
            string ext = Path.GetExtension(path);
            switch (ext)
            {
                case ".txt": return File.ReadAllText(path);
                case ".pdf": return PDF.Text(path);
                case ".docx": return Docx.Text(path);
                default: return null;
            }
        }
        #endregion

		private void _btnSave_Click(object sender, EventArgs e)
		{
			try
			{
				this._pbrProcessing.Style = ProgressBarStyle.Marquee;

				if (this._gst != null) this._gst.Save(Application.StartupPath + "\\Corpus\\" + this._odgOpenDocument.FileName.GetHashCode() +".txt");
			}
			catch (System.Exception exc)
			{
				MessageBox.Show(exc.Message);
			}
		}

		private void Test_Click(object sender, EventArgs e)
		{
			try
			{
				IDF idf = new IDF(Application.StartupPath + "\\Corpus\\" + "-1696877512.txt");
				if (idf.Search("cây hậu tố"))
				{
					MessageBox.Show("Thanh cong!!!");
				}
				else
				{
					MessageBox.Show("Ngu!!!");
				}
			}
			catch (System.Exception exc)
			{
				MessageBox.Show(exc.Message);
			}
		}

		private void _btnOpenX_Click(object sender, EventArgs e)
		{
			if (this._brOpenX.ShowDialog() == DialogResult.OK)
			{
				string[] paths = Directory.GetFiles(this._brOpenX.SelectedPath);
				for (int i = 0; i < paths.Length; i++)
				{
					try
					{
						string content = PDF.Text(paths[i]);
						content = GST.Preprocess(content);
						File.WriteAllText(Application.StartupPath + "\\Corpus\\" + paths[i].GetHashCode() + ".txt", content);
					}
					catch (System.Exception exc)
					{
						MessageBox.Show(exc.Message);
					}
				}
			}
		}
		private void Process(string[] paths)
		{
// 			new Thread(new ThreadStart(() =>
// 			{
// 				for (int i = 0; i < paths.Length; i++)
// 				{
// 					string content = ToText(paths[i]);
// 					GST.IsReport = false;
// 					GST.New(GST.)
// 				}
// 			})).Start();
		}
    }
}
